<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
      <el-form-item label="计划名称" prop="scheduleName">
        <el-input v-model="form.scheduleName" placeholder="请输入计划名称" class="my-input" />
      </el-form-item>
      <el-form-item label="来源类型" prop="scheduleSourceType">
        <el-select
          v-model="form.scheduleSourceType"
          placeholder="请选择来源类型" class="my-input"
        >
          <el-option
            v-for="dict in getScheduleSource"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="scheduleOrder" v-show="form.scheduleSourceType === '0'">
        <el-input v-model="form.scheduleOrder" placeholder="请输入订单编号" class="my-input" />
      </el-form-item>
      <el-form-item label="成品名称" prop="schedulePdCode">
        <MyPopoverBtn placeholder="请选择产品" :content="form.selectedGood.pdName" class="my-input"
                      @click="handleToChangeProduct"
        />
      </el-form-item>
      <el-form-item label="成品编号" prop="schedulePdCode">
        <el-input v-model="form.selectedGood.pdCode" class="my-input" disabled />
      </el-form-item>
      <el-form-item label="规格型号" prop="schedulePdCode">
        <el-input v-model="form.selectedGood.pdSpecType" class="my-input" disabled />
      </el-form-item>
      <el-form-item label="成品类型" prop="schedulePdCode">
        <el-input
          v-model="form.selectedGood.gbsGoodClass ? form.selectedGood.gbsGoodClass.gcName : form.selectedGood.pdGoodClass"
          class="my-input" disabled
        />
      </el-form-item>
      <el-form-item label="单位" prop="schedulePdCode">
        <el-input
          v-model="form.selectedGood.gbsGoodUnit ? form.selectedGood.gbsGoodUnit.guName : form.selectedGood.pdUnitType"
          class="my-input" disabled
        />
      </el-form-item>
      <el-form-item label="计划数量" prop="scheduleNum">
        <el-input v-model="form.scheduleNum" placeholder="请输入计划数量" class="my-input" />
      </el-form-item>
      <el-form-item label="开工时间" prop="scheduleStart">
        <el-date-picker clearable
                        v-model="form.scheduleStart"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择开工时间"
                        class="my-input"
        />
      </el-form-item>
      <el-form-item label="完工时间" prop="scheduleComplete">
        <el-date-picker clearable
                        v-model="form.scheduleComplete"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择完工时间"
                        class="my-input"
        />
      </el-form-item>
      <el-form-item label="需求日期" prop="scheduleRequire">
        <el-date-picker clearable
                        v-model="form.scheduleRequire"
                        type="datetime"
                        format="yyyy-MM-dd HH:mm:ss"
                        value-format="yyyy-MM-dd HH:mm:ss"
                        placeholder="请选择需求日期"
                        class="my-input"
        />
      </el-form-item>
      <el-form-item label="备注" prop="scheduleDesc" class="my-desc">
        <el-input v-model="form.scheduleDesc" type="textarea" placeholder="请输入内容"
                  :autosize="{ minRows: 3 }"
        />
      </el-form-item>
    </el-form>

    <el-divider>
      <div class="my-divider">BOM组成</div>
    </el-divider>
    <el-button type="primary" @click="handleToAddBOM">添加</el-button>
    <el-descriptions :column="2">
      <el-descriptions-item label="BOM编号">
        {{ form.scheduleBom }}
      </el-descriptions-item>
      <el-descriptions-item label="BOM版本">{{ form.scheduleBomVersion }}</el-descriptions-item>
    </el-descriptions>
    <el-table :data="bomMaterials">
      <el-table-column type="index" align="center" label="序号" />
      <el-table-column label="产品编号" align="center" prop="gbsMaterial.pdCode" />
      <el-table-column label="产品名称" align="center" prop="gbsMaterial.pdName" />
      <el-table-column label="规格型号" align="center" prop="gbsMaterial.pdSpecType" />
      <el-table-column label="单位" align="center" prop="gbsMaterial.gbsGoodUnit.guName" />
      <el-table-column label="BOM编号" align="center" prop="bmBomCode" />
      <el-table-column label="BOM版本" align="center" prop="bmBomVersion" />
      <el-table-column label="使用量" align="center" prop="bmUse" />
      <el-table-column label="使用比例" align="center" prop="bmUse" />
    </el-table>


    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />

    <!--    product-dialog-->
    <MyGoodDialog title="选择产品"
                  v-model="productDialogVisible"
                  :good.sync="form.selectedGood"
                  :showTabs="false"
                  :single-mode="true"
                  show-content="both"
    />

    <!--    bom-dialog-->
    <el-dialog title="选择BOM"
               :visible.sync="bomDialogVisible"
               width="60%"
    >
      <el-descriptions :column="4">
        <el-descriptions-item label="产品名称">{{ form.selectedGood ? form.selectedGood.pdName : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="产品编号">{{ form.selectedGood ? form.selectedGood.pdCode : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="规格型号">{{ form.selectedGood ? form.selectedGood.pdSpecType : '' }}
        </el-descriptions-item>
        <el-descriptions-item label="单位">
          {{ form.selectedGood && form.selectedGood.gbsGoodUnit ? form.selectedGood.gbsGoodUnit.guName : '' }}
        </el-descriptions-item>
      </el-descriptions>
      <el-table :data="bomList" class="my-table" highlight-current-row @current-change="handleCurrentBOM">
        <el-table-column type="index" align="center" label="序号" />
        <el-table-column label="BOM编号" align="center" prop="bomCode" />
        <el-table-column label="版本号" align="center" prop="bomVersion" />
        <el-table-column label="默认BOM" align="center" prop="isDefault" />
        <el-table-column label="日产量" align="center" prop="bomDailyOutput" />
      </el-table>
      <div slot="footer">
        <el-button @click="closeBOMDialog">取 消</el-button>
        <el-button type="primary" @click="okBOMDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addSchedule, getSchedule, updateSchedule } from '@/api/yyj/pro/schedule'
import { getBomByPdCode } from '@/api/yyj/gbs/bom'
import { listBomMaterial } from '@/api/yyj/gbs/bomMaterial'
import MyPopoverBtn from '@/components/MyPopoverBtn/index.vue'
import MyGoodDialog from '@/components/MyGoodDialog/index.vue'
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'

export default {
  name: 'ScheduleChange',
  dicts: ['yyj_schedule_source'],
  components: { MyConfirmBtnGroup, MyGoodDialog, MyPopoverBtn },
  data() {
    return {
      backPage: '/pro/schedule',
      bomDialogVisible: false,
      productDialogVisible: false,
      // 表单参数
      form: {
        selectedGood: []
      },
      // 表单校验
      rules: {
        scheduleName: [
          { required: true, message: '计划名称不能为空', trigger: 'blur' }
        ],
        scheduleNum: [
          { required: true, message: '计划数量不能为空', trigger: 'blur' }
        ],
        scheduleStatus: [
          {
            required: true,
            message: '计划状态不能为空',
            trigger: 'change'
          }
        ],
        scheduleSourceType: [
          { required: true, message: '来源类型不能为空', trigger: 'change' }
        ],
        // scheduleOrder: [
        //   {
        //     required: false, trigger: 'blur', validator: (rule, val, callback) => {
        //       if (this.form.scheduleSourceType === '0') {
        //         callback()
        //       } else {
        //         callback('订单编号不能为空')
        //       }
        //     }
        //   }
        // ],
        scheduleBom: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback('BOM不为空')
              }
              callback()
            }
          }
        ]
      },
      // dialog-bom 中的数据
      bomList: [],
      // 预选的bom
      preSelectedBOM: {},
      // 返回的treeMaterials
      bomMaterials: []
    }
  },
  created() {
    const scheduleCode = this.$route.params && this.$route.params.scheduleCode
    if (scheduleCode) {
      this.getDetail(scheduleCode)
    }
  },
  computed: {
    getScheduleSource() {
      return this.dict.type.yyj_schedule_source
    }
  },
  methods: {
    // 获取详情
    async getDetail(scheduleCode) {
      const res = await getSchedule(scheduleCode)
      this.form = res.data
      this.form.selectedGood = this.form.gbsGood
      await this.getMaterials({
        bmBomCode: this.form.scheduleBom,
        bmBomVersion: this.preSelectedBOM.scheduleBomVersion
      })
    },
    // 选择bom
    handleCurrentBOM(val) {
      console.log(val)
      this.preSelectedBOM = val
    },
    // 确定bom-dialog
    async okBOMDialog() {
      this.form.scheduleBom = this.preSelectedBOM.bomCode
      this.form.scheduleBomVersion = this.preSelectedBOM.bomVersion
      await this.getMaterials({
        bmBomCode: this.preSelectedBOM.bomCode,
        bmBomVersion: this.preSelectedBOM.bomVersion
      })
      this.closeBOMDialog()
    },
    // 关闭bom-dialog
    closeBOMDialog() {
      this.bomDialogVisible = false
    },
    // 去添加BOM
    async handleToAddBOM() {
      console.log('tt ', this.form.selectedGood.pdCode)
      if (!this.form.selectedGood.pdCode) {
        this.$modal.msgError('请选择产品')
        return
      }
      // 查询产品的bom
      const res = await getBomByPdCode(this.form.selectedGood.pdCode)
      console.log(res)
      this.bomList = res.data
      this.bomDialogVisible = true
    },
    // 通过 bomCode 和 bomVersion 找到对应的物料
    async getMaterials(params) {
      const res = await listBomMaterial(params)
      this.bomMaterials = res.data
    },
    // 切换产品
    handleToChangeProduct() {
      this.form.scheduleBom = ''
      this.form.scheduleBomVersion = ''
      this.bomMaterials = []
      this.productDialogVisible = true
    },
    // 表单重置
    reset() {
      this.form = {}
      this.resetForm('form')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (!this.form.scheduleBom || !this.form.scheduleBomVersion) {
            this.$modal.msgError('请选择Bom')
            return
          }
          this.form.schedulePdCode = this.form.selectedGood.pdCode
          this.$modal.loading('正在提交...')
          if (this.form.scheduleCode != null) {
            await updateSchedule(this.form)
            this.$modal.msgSuccess('修改成功')
          } else {
            await addSchedule(this.form)
            this.$modal.msgSuccess('新增成功')
          }
          this.afterSubmit()
        }
      })
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    }
  }
}
</script>

<style scoped lang="scss">
@import "@/assets/styles/yyj/change";

.my-table {
  min-height: 300px;
  max-height: 300px;
}
</style>
